/**
 *
 */
package com.darren.befriend;

import java.lang.reflect.Array;

import com.darren.befriend.utilities.LogUtil;
import com.darren.befriend.utilities.MySharedPreferences;
import com.darren.befriend.utilities.Utilities;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.parse.LocationCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseInstallation;
import com.parse.ParseObject;
import com.parse.ParseUser;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.location.Address;
import android.location.Criteria;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author ubuntu
 * 
 */
@SuppressWarnings("unused")
public class BaseActivity extends FragmentActivity implements OnClickListener {

	private ImageButton mHeaderLeftBtn, mHeaderRightBtn;
	private ImageView mTitleImg;
	private TextView mTitleTxt;
	protected ParseUser mParseUser;
	protected ImageLoader mImageLoader;
	protected DisplayImageOptions mOptions;
	public static ParseGeoPoint mGeoPoint;
	private static boolean isAppWentToBg = false;
	private static boolean isWindowFocused = false;
	private static boolean isMenuOpened = false;
	private static boolean isBackPreesed = false;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		int layoutId = addContent();
		setContentView(layoutId);
		MySharedPreferences.init(getApplicationContext());
		initView();

		// Register service
		IntentFilter screenOffOnFilter = new IntentFilter(
				Intent.ACTION_SCREEN_ON);
		screenOffOnFilter.addAction(Intent.ACTION_SCREEN_OFF);
		registerReceiver(screenOnOffReceiver, screenOffOnFilter);
	}

	/**
	 * Set layout xml file and other flags
	 * 
	 * @return xml layout id
	 * */
	protected int addContent() {

		return R.layout.activity_base;
	}

	/**
	 * Initiation views, get/set views
	 * */
	protected void initView() {

		new GetCurrentLocationAsyns().execute();
		mImageLoader = ImageLoader.getInstance();

		if (!mImageLoader.isInited()) {

			mImageLoader.init(ImageLoaderConfiguration
					.createDefault(BaseActivity.this));
		}

		if (mOptions == null) {

			mOptions = new DisplayImageOptions.Builder()
					.showImageOnLoading(R.drawable.tmp_profile)
					.showImageForEmptyUri(R.drawable.tmp_profile)
					.showImageOnFail(R.drawable.tmp_profile)
					.cacheInMemory(true).cacheOnDisc(true)
					.considerExifParams(true)
					.bitmapConfig(Bitmap.Config.RGB_565).build();
		}

		RelativeLayout headerLayout = (RelativeLayout) findViewById(R.id.header_layout);
		if (headerLayout != null) {

			mHeaderLeftBtn = (ImageButton) findViewById(R.id.header_left_btn);
			mHeaderRightBtn = (ImageButton) findViewById(R.id.header_right_btn);
			mTitleImg = (ImageView) findViewById(R.id.header_title_img);
			mTitleTxt = (TextView) findViewById(R.id.header_title_txt);
			mHeaderLeftBtn.setOnClickListener(this);
			mHeaderRightBtn.setOnClickListener(this);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.header_left_btn:

			break;
		case R.id.header_right_btn:

			break;

		default:
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onResume()
	 */
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub

		if (screenOnOffReceiver != null) {

			unregisterReceiver(screenOnOffReceiver);
		}

		LogUtil.e("Base acitivity", "onDestroy");
		super.onDestroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		appWillEnterForeground();
		super.onStart();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		isBackPreesed = true;
		super.onBackPressed();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onStop()
	 */
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub

		appGoingToBackgroud();
		super.onStop();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onWindowFocusChanged(boolean)
	 */
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		// TODO Auto-generated method stub

		isWindowFocused = hasFocus;
		if (isBackPreesed && !hasFocus) {

			isBackPreesed = false;
			isWindowFocused = true;
		}

		super.onWindowFocusChanged(hasFocus);
	}

	/**
	 * Called when application is going to background
	 * */
	private void appGoingToBackgroud() {

		if (!isWindowFocused) {

			LogUtil.e("App status", "App is going to background");
			isAppWentToBg = true;
			if (mParseUser != null) {

				mParseUser.put("Status", false);
				try {

					ParseObject meInfo = mParseUser.getParseObject("MeInfo");
					ParseObject filter = mParseUser.getParseObject("Filter");
					meInfo.saveInBackground();
					filter.saveInBackground();
					mParseUser.saveInBackground();
				} catch (Exception e) {
					// TODO Auto-generated catch block

				}
			}
		}
	}

	/**
	 * Called when application enter foreground
	 * */
	private void appWillEnterForeground() {

		if (isAppWentToBg) {

			new GetDataWhenBack().execute();
		}
	}

	public ParseUser getCurrentUser() {
		return mParseUser = ParseUser.getCurrentUser();
	}

	public void setData(String key, String value) {
		if (mParseUser != null) {
			mParseUser.put(key, value);
		}
	}

	public void setData(String key, int value) {
		if (mParseUser != null) {
			mParseUser.put(key, value);
		}
	}

	public void setData(String key, Array[] value) {
		if (mParseUser != null) {
			mParseUser.put(key, value);
		}
	}

	public ImageLoader getImageLoader() {
		return mImageLoader;
	}

	public DisplayImageOptions getOptions() {
		return mOptions;
	}

	BroadcastReceiver screenOnOffReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			LogUtil.e("ScreenOnOffReceiver", intent.getAction());
			if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

				LogUtil.e("App status", "App is going to background");
				isAppWentToBg = true;
				if (mParseUser != null) {

					mParseUser.put("Status", false);
					try {

						mParseUser.saveInBackground();
						ParseObject meInfo = mParseUser
								.getParseObject("MeInfo");
						ParseObject filter = mParseUser
								.getParseObject("Filter");
						meInfo.saveInBackground();
						filter.saveInBackground();
					} catch (Exception e) {

					}
				}
			} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

				// appWillEnterForeground();
				if (mParseUser != null) {

					mParseUser.put("Status", true);
					mParseUser.saveInBackground();
				}
			}
		}
	};

	protected class GetCurrentLocationAsyns extends
			AsyncTask<Void, Void, Criteria> {

		@Override
		protected Criteria doInBackground(Void... params) {

			Criteria criteria = new Criteria();
			criteria.setAccuracy(Criteria.ACCURACY_LOW);
			criteria.setAltitudeRequired(false);
			criteria.setBearingRequired(false);
			criteria.setCostAllowed(true);
			criteria.setPowerRequirement(Criteria.POWER_LOW);
			return criteria;
		}

		@Override
		protected void onPostExecute(Criteria result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			ParseGeoPoint.getCurrentLocationInBackground(5000, result,
					new LocationCallback() {

						@Override
						public void done(ParseGeoPoint geoPoint,
								ParseException pe) {
							// TODO Auto-generated method stub

							if (pe != null) {

								Address address = Utilities
										.getCurrentLocation(getApplicationContext());
								if (address != null) {

									geoPoint = new ParseGeoPoint(address
											.getLatitude(), address
											.getLongitude());
								}
							}

							if (geoPoint != null) {

								mGeoPoint = geoPoint;
								LogUtil.e("getCurrentLocationInBackground",
										geoPoint.getLatitude() + " - "
												+ geoPoint.getLongitude());
							}
						}
					});
		}
	}

	private class GetDataWhenBack extends AsyncTask<Void, Void, Void> {

		/*
		 * (non-Javadoc)
		 * 
		 * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
		 */
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			LogUtil.e("App status", "App is going to forceground");
			isAppWentToBg = false;
			if (mParseUser != null) {

				try {

					mParseUser.fetchIfNeeded();
					mParseUser.put("Filter", mParseUser
							.getParseObject("Filter").fetch());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
				}

				try {

					mParseUser.fetchIfNeeded();
					mParseUser.put("Filter", mParseUser
							.getParseObject("Filter").fetch());
				} catch (ParseException e) {
					// TODO Auto-generated catch block
				}

				try {

					mParseUser.put("Status", true);
					mParseUser.save();
					if (mGeoPoint != null) {

						mParseUser.put("Position", mGeoPoint);

					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
				}
			}

			return null;
		}
	}
}
